Base.namespace('Base.mobile');

try
{
    //API key for http://openlayers.org. Please get your own at
    //http://bingmapsportal.com/ and use that instead. -- got one.
    var apiKey = "Ao5Ew1XnxVey8Mh0jgfL32mbQN1pNLQoDv48u1r5BJrGsf8r0Bach7FYO5wTpbHl";
    
    //initialize map when page ready
    var map;
    var gg = new OpenLayers.Projection("EPSG:4326");
    var sm = new OpenLayers.Projection("EPSG:900913");
    OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
    
    OpenLayers.Util.onImageLoadError = function(){this.src='../images/blank.gif';}
    OpenLayers.Tile.Image.useBlankTile=false;
}
catch(e)
{
    console.log("Map: error creating this type...please ignore this error if you are not using OpenLayers");
}


/**
 * Class: Base.mobile.Map
 * @class 
 */
Base.mobile.MapStatic = {

    ui      : null,
    map     : null,
    style   : null,
    vectors : null,
    select  : null,

    // next 4-5 params relate to the vector layer...
    // NOTE: code also assumes that feature also has 'name', 'mode' and 'street_id' attributes 
    wfs_url     : "/cc/geoserver/wfs/",
    wfs_feature : "PilotSts_wm",
    geom_name   : "the_geom",
    namespace   : "http://maps.trimet.org/bh",
    srs         : "EPSG:900913",

    /** */
    initialize : function(config)
    {
        if(Base.isLocalHost())
        {
            this.wfs_url     = "test/wfs-small.xml";

            /* 
            // wfs-medium.xml is a WFS snapshot taken of the trimet:bike_route features, hence the different attributes from PilotSts_wm
            this.wfs_url     = "test/wfs-medium.xml";
            this.geom_name   = "geom";
            this.wfs_feature = "bike_route";
            this.namespace   = "http://maps.trimet.org/trimet";
            */
        }
        Base.configure(this, config);

        this.geolocate = new OpenLayers.Control.Geolocate({
             id: 'locate-control',
             geolocationOptions: {
                 enableHighAccuracy: false,
                 maximumAge: 0,
                 timeout: 7000
             }
        });

        // http://maps5.trimet.org/cc/geoserver/wfs?service=WFS&srsName=epsg:4326&version=1.0.0&request=GetFeature&typeName=trimet:bike_route&maxFeatures=5000
        // http://maps5.trimet.org/cc/geoserver/wfs?service=WFS&&propertyName=street_id,geom&srsName=epsg:4326&version=1.0.0&request=GetFeature&typeName=trimet:bike_route&maxFeatures=500
        this.map = new OpenLayers.Map({
            div: "map",
            controls: [
                 new OpenLayers.Control.Attribution(),
                 new OpenLayers.Control.TouchNavigation({
                     dragPanOptions: {
                         interval: 100,
                         enableKinetic: true
                     }
                 }),
                 this.geolocate
            ],
            layers: this.getBaseLayers(),
            projection: 'epsg:900913',
            center: new OpenLayers.LonLat(-13656000, 5704000),
            zoom: 15
        });

        var proto = new OpenLayers.Protocol.WFS({
            url: this.wfs_url,
            geometryName: this.geom_name,
            featureType: this.wfs_feature,
            multipleSelect: true,
            srsName: this.srs,
            srsNameInQuery:true,
            featureNS: this.namespace
        });

        this.style = new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
                fillColor: "#ffcc66",
                strokeColor: "#939797",
                strokeWidth: 4,
                graphicZIndex: 1,
                strokeOpacity: 0.50
            }),
            "temporary": new OpenLayers.Style({
                fillColor: "#66ccff",
                strokeColor: "#09F6EF",
                strokeWidth: 4,
                graphicZIndex: 2,
                cursor : "pointer", 
                strokeOpacity: 0.50
            }),
            "select": new OpenLayers.Style({
                fillColor: "#66ccff",
                strokeColor: "#3399ff",
                strokeWidth: 4,
                graphicZIndex: 2,
                strokeOpacity: 0.50
            })
        });

        //create a lookup table with different symbolizers for each value
        var lookup = {
            0: {strokeColor: "#939797"}, //grey
            1: {strokeColor: "#FF4000"}, //red
            2: {strokeColor: "#FFB700"}, //orange
            3: {strokeColor: "#F2FF00"}, //yellow
            4: {strokeColor: "#00FF44"}, //green
            5: {strokeColor: "#118F33"} //dark green
        }

        //add the rules from the above lookup table, with the keys mapped to the "vote" property of the features, for the "default" intent
        this.style.addUniqueValueRules("default", "vote", lookup)

        //var strat = new OpenLayers.Strategy.Fixed(); // simple strategy that requests features once and never requests new data (fear using this, as load might take 30 seconds)
        var strat = new OpenLayers.Strategy.BBOX();  // strategy that reads new features when the viewport invalidates some bounds
        this.vectors = new OpenLayers.Layer.Vector("Bike Routes", {
            strategies: [strat],
            protocol: proto,
            styleMap: this.style
        });
        this.vectors.events.register("loadstart", this, this.clearVoteData);
        this.vectors.events.register("loadend",   this, this.applyVotesToFeatures);

        this.map.addLayers([this.vectors]);
    },

    /** */
    clearVoteData : function()
    {
        if(this.ui)
            this.ui.refreshAllVotesData();
    },

    /** */ 
    applyVotesToFeatures : function()
    {
        if(this.vectors == null || this.vectors.features == null || this.ui == null) return;

        for(var i in this.vectors.features)
        {
            var f = this.vectors.features[i].attributes;
            var v = this.ui.getVote(f.street_id);
            if(v && v.avg)
                f.vote = v.avg;  // vote average added
            else
                f.vote = 0;      // default
        }
        this.vectors.redraw();
    },

    /** return array of base layers */
    addSelectControl : function(on, off)
    {
        this.select = new Base.SelectControl({map:this.map, layers:[this.vectors], featurePopupOn:on, featurePopupOff:off});
    },

    /** return array of base layers */
    getBaseLayers : function()
    {
       return [ 
	   
         /**new OpenLayers.Layer.CloudMade("CrowdCycle CloudMade Base", {
		 	key: '4f492e496b9d4cfb9a5ca73cd8fd94b1'
		 }),*/
			
		 new OpenLayers.Layer.OSM("OpenStreetMap", null, {
             transitionEffect: 'resize'
         }),     
         new OpenLayers.Layer.Bing({
             key: apiKey,
             type: "AerialWithLabels",
             name: "Bing Aerial + Labels",
             transitionEffect: 'resize'
		 }),
         new OpenLayers.Layer.Bing({
             key: apiKey,
             type: "Road",
             name: "Bing Road",
             transitionEffect: 'resize'
         }),
         new OpenLayers.Layer.Bing({
             key: apiKey,
             type: "Aerial",
             name: "Bing Aerial",
             transitionEffect: 'resize' 
         })
		 /**,
		 //metro bike route base layer (styled by type)-- not working in OL even though the request works fine in browser
		 new OpenLayers.Layer.WMS(
		     "Metro Bike Routes Base",
		     "http://maps5.trimet.org/cc/geoserver/wms/reflect",
		     {layers: "bh:PilotSts_wm" //, srs: 'EPSG:900913' 
		 }),
		
		 // tm base layer -- not working either
         new OpenLayers.Layer.WMS(
             "TriMet Base Map", 
             "http://maps5.trimet.org/wms/reflect",
             {layers: "currentOSPN" //, srs: 'EPSG:900913'
         }) 
		 */
		
        ]
    },

    CLASS_NAME: "Base.mobile.Map"
}
Base.mobile.Map = new Base.Class(Base.mobile.MapStatic);

